package com.trace.demo.controller;

import com.trace.demo.entity.TodoItem;
import com.trace.demo.entity.User;
import com.trace.demo.repository.TodoItemRepository;
import com.trace.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.HashMap;
import java.util.Optional;

/**
 * 待办事项控制器
 */
@RestController
@RequestMapping("/api/todos")
public class TodoController {

    private final TodoItemRepository todoItemRepository;
    private final UserRepository userRepository;

    @Autowired
    public TodoController(TodoItemRepository todoItemRepository, UserRepository userRepository) {
        this.todoItemRepository = todoItemRepository;
        this.userRepository = userRepository;
    }

    /**
     * 获取用户的待办事项列表
     * @param userId 用户ID
     * @return 待办事项列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getUserTodos(@PathVariable Long userId) {
        return ResponseEntity.ok(todoItemRepository.findByUserId(userId));
    }

    /**
     * 添加待办事项
     * @param userId 用户ID
     * @param todoItem 待办事项
     * @return 保存的待办事项
     */
    @PostMapping("/user/{userId}")
    public ResponseEntity<?> addTodoItem(@PathVariable Long userId, @RequestBody TodoItem todoItem) {
        try {
            // 查找用户
            Optional<User> userOpt = userRepository.findById(userId);
            if (!userOpt.isPresent()) {
                Map<String, Object> errorMap = createErrorMap("User not found with id: " + userId);
                return ResponseEntity.badRequest().body(errorMap);
            }

            // 设置用户和创建时间
            User user = userOpt.get();
            todoItem.setUser(user);
            todoItem.setCreatedAt(LocalDateTime.now());

            // 保存待办项
            TodoItem savedItem = todoItemRepository.save(todoItem);
            return ResponseEntity.ok(savedItem);
        } catch (Exception e) {
            Map<String, Object> errorMap = createErrorMap("添加待办项失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorMap);
        }
    }

    /**
     * 更新待办事项
     * @param todoId 待办事项ID
     * @param todoItem 待办事项
     * @return 更新后的待办事项
     */
    @PutMapping("/{todoId}")
    public ResponseEntity<?> updateTodoItem(@PathVariable Long todoId, @RequestBody TodoItem todoItem) {
        try {
            // 查找现有的待办项
            Optional<TodoItem> existingItemOpt = todoItemRepository.findById(todoId);
            if (!existingItemOpt.isPresent()) {
                return ResponseEntity.notFound().build();
            }

            // 设置必要属性
            TodoItem existingItem = existingItemOpt.get();
            todoItem.setId(todoId);
            todoItem.setUser(existingItem.getUser());
            if (existingItem.getCreatedAt() != null) {
                todoItem.setCreatedAt(existingItem.getCreatedAt());
            } else {
                todoItem.setCreatedAt(LocalDateTime.now());
            }

            // 保存更新后的待办项
            TodoItem updatedItem = todoItemRepository.save(todoItem);
            return ResponseEntity.ok(updatedItem);
        } catch (Exception e) {
            Map<String, Object> errorMap = createErrorMap("更新待办项失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorMap);
        }
    }

    /**
     * 删除待办事项
     * @param todoId 待办事项ID
     * @return 响应结果
     */
    @DeleteMapping("/{todoId}")
    public ResponseEntity<?> deleteTodoItem(@PathVariable Long todoId) {
        try {
            if (todoItemRepository.existsById(todoId)) {
                todoItemRepository.deleteById(todoId);
                return ResponseEntity.ok().build();
            }
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            Map<String, Object> errorMap = createErrorMap("删除待办项失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorMap);
        }
    }

    /**
     * 标记待办事项为已完成
     * @param todoId 待办事项ID
     * @return 更新后的待办事项
     */
    @PutMapping("/{todoId}/complete")
    public ResponseEntity<?> markTodoItemAsCompleted(@PathVariable Long todoId) {
        try {
            // 查找待办项
            Optional<TodoItem> todoItemOpt = todoItemRepository.findById(todoId);
            if (!todoItemOpt.isPresent()) {
                return ResponseEntity.notFound().build();
            }

            // 标记为已完成
            TodoItem todoItem = todoItemOpt.get();
            todoItem.setCompleted(true);
            todoItem.setCompletedAt(LocalDateTime.now());

            // 保存更新
            TodoItem updatedItem = todoItemRepository.save(todoItem);
            return ResponseEntity.ok(updatedItem);
        } catch (Exception e) {
            Map<String, Object> errorMap = createErrorMap("标记待办项失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorMap);
        }
    }

    /**
     * 创建错误响应Map
     * @param errorMessage 错误信息
     * @return 错误响应Map
     */
    private Map<String, Object> createErrorMap(String errorMessage) {
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("error", errorMessage);
        return errorMap;
    }
}
